package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"

	"gitee.com/239103/flight_demo/models"
	"github.com/bxcodec/faker"
	_ "github.com/go-sql-driver/mysql"
	"github.com/gorilla/mux"
)

var myDB *sql.DB

const (
	// DBHost - DB host string, IP address or hostname
	DBHost = "192.168.50.51"
	// DBPort - DB service port
	DBPort = ": 3306"
	// DBUser - DB user
	DBUser = "flight"
	// DBPass - DB user password
	DBPass = "sf123456"
	// DBDbase - DB name
	DBDbase = "flight"
)

// ErrHandler - error handle function
func ErrHandler(err error) {
	if err != nil {
		log.Fatal(err.Error())
	}
}

func init() {
	// sample DSN:username:password@protocol(address)/dbname?pa
	//ram=value
	dbConn := fmt.Sprintf("%s:%s@tcp(%s)/%s", DBUser, DBPass, DBHost, DBDbase)
	myDB, _ = sql.Open("mysql",
		dbConn+"?loc=Local&autocommit=true")
	err := myDB.Ping()
	ErrHandler(err)
}

// FlightHandler - api handle function
func FlightHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Pragma", "no-cache")
	w.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
	w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
	w.Header().Set("content-type", "application/json")
	urlParams := mux.Vars(r)
	id := urlParams["id"]
	ReadFlight := models.Flight{}
	err := myDB.QueryRow("select * from flight where id=?", id).Scan(
		&ReadFlight.ID, &ReadFlight.Code, &ReadFlight.Source, &ReadFlight.Destination, &ReadFlight.StartTime, &ReadFlight.EndTime, &ReadFlight.Spend, &ReadFlight.CreateTM, &ReadFlight.ModifyTM, &ReadFlight.Operator, &ReadFlight.Tags)
	switch {
	case err == sql.ErrNoRows:
		fmt.Fprintf(w, "No sush flight information")
	case err != nil:
		ErrHandler(err)
	default:
		output, _ := json.Marshal(ReadFlight)
		fmt.Fprintf(w, string(output))
	}
}

func main() {
	var err error
	var a models.Flight
	var id int64 = 1
	// 清空表，生成数据
	myDB.Exec("truncate table flight")
	//start := time.Now()
	tx, _ := myDB.Begin()
	for i := 1; i <= 200; i++ {
		_ = faker.FakeData(&a)
		fmt.Printf("%+v", a)
		_, err = tx.Exec("INSERT INTO flight(id,code,source,destination,starttime,endtime,spend,createtm,modifytm,operator,tags) "+
			"values(?,?,?,?,?,?,?,?,?,?,?)", id, a.Code, a.Source, a.Destination, time.Now(), time.Now(), a.Spend, time.Now(), time.Now(), a.Operator, a.Tags)
		ErrHandler(err)
		id++
	}
	err = tx.Commit()
	ErrHandler(err)

	//输出建库所用的时间
	//end := time.Now()
	//fmt.Println("Total inserting seconds:", end.Sub(start).Seconds())

	routes := mux.NewRouter()
	routes.HandleFunc("/api/flight/{id:[0-9]+}", FlightHandler)
	http.Handle("/", routes)
	http.ListenAndServe(":8080", nil)

}
